<template>
    <div class="global-search-container">
        <el-form :inline="true" ref="form" class="global-search" :model="form">
            <el-form-item label="机构：">
                <el-select v-model="form.mechanism" filterable class="mechanism" @change="setDepartmentList" size="small" placeholder="请选择">
                    <el-option
                        v-for="item in mechanismList"
                        :key="item.id"
                        :label="item.name"
                        :value="item.id">
                    </el-option>
                </el-select>
            </el-form-item>
            <el-form-item label="出院科室：" v-if="!isDataPackge">
                <el-cascader
                    ref="cascaderSelector"
                    :key="isResouceShow"
                    class="go-out"
                    v-model="form.department"
                    :show-all-levels="false"
                    :options="departmentList"
                    :props="{ checkStrictly: true, emitPath: false, value: 'id', label: 'name' }"
                    filterable
                    size="small">
                </el-cascader>
            </el-form-item>
            <el-form-item label="编码员：" v-if="!isDataPackge">
                <el-select v-model="form.coder" filterable class="coder" size="small" placeholder="请选择">
                    <el-option v-if="coderList.length > 0" key="0" label="全部" value="0"></el-option>
                    <el-option
                        v-for="item in coderList"
                        :key="item.value"
                        :label="item.label"
                        :value="item.label">
                    </el-option>
                </el-select>
            </el-form-item>
            <el-form-item label="出院日期：" v-if="!isDataPackge">
                <el-select v-model="datePickerOut.timeUnit" v-if="!isDataPackge" class="time-unit" size="small" placeholder="请选择">
                    <el-option label="月" value="month"></el-option>
                    <el-option label="季度" value="quarter"></el-option>
                    <el-option label="年" value="year"></el-option>
                </el-select>
                <el-date-picker
                    class="year-month"
                    v-model="datePickerOut.yearMonth"
                    v-if="!isDataPackge"
                    :type="datePickerOut.timeUnit === 'month' ? 'month' : 'year'"
                    value-format="yyyy-MM-dd"
                    popper-class="custom-date-width"
                    :clearable="false"
                    size="small">
                </el-date-picker>
                <el-select v-if="datePickerOut.timeUnit === 'quarter' && !isDataPackge" class="quarter" v-model="datePickerOut.quarter" size="small" placeholder="请选择">
                    <el-option label="第一季度" value="1"></el-option>
                    <el-option label="第二季度" value="2"></el-option>
                    <el-option label="第三季度" value="3"></el-option>
                    <el-option label="第四季度" value="4"></el-option>
                </el-select>
            </el-form-item>
            <el-form-item label="上传日期：" v-if="isDataPackge">
                <el-select v-model="datePickerUpload.timeUnit" v-if="isDataPackge" class="time-unit" size="small" placeholder="请选择">
                    <el-option label="月" value="month"></el-option>
                    <el-option label="季度" value="quarter"></el-option>
                    <el-option label="年" value="year"></el-option>
                </el-select>
                <el-date-picker
                    class="year-month"
                    v-model="datePickerUpload.yearMonth"
                    v-if="isDataPackge"
                    :type="datePickerUpload.timeUnit === 'month' ? 'month' : 'year'"
                    popper-class="custom-date-width"
                    :clearable="false"
                    value-format="yyyy-MM-dd"
                    size="small">
                </el-date-picker>
                <el-select v-if="datePickerUpload.timeUnit === 'quarter' && isDataPackge" class="quarter" v-model="datePickerUpload.quarter" size="small" placeholder="请选择">
                    <el-option label="第一季度" value="1"></el-option>
                    <el-option label="第二季度" value="2"></el-option>
                    <el-option label="第三季度" value="3"></el-option>
                    <el-option label="第四季度" value="4"></el-option>
                </el-select>
            </el-form-item>
            <el-form-item>
                <el-button class="sub-btn" type="primary" size="small" @click="submitSearch">查询</el-button>
            </el-form-item>
        </el-form>
        <el-checkbox v-model="form.lastCount" @change="submitSearch" v-if="!isDataPackge && isShowLast && overviewIsShowLast">末次统计</el-checkbox>
    </div>
</template>

<script>
    import { getCoderList } from '@/api/global/index'
    import {Bus} from '@/utils/bus'
    import Cookie from 'js-cookie'

    export default {
        name: 'GlobalSearch',
        data () {
            return {
                // 表单
                form: {
                    mechanism: '',
                    department: '',
                    coder: '',
                    lastCount: true,
                    cykb: '',
                    cybf: ''
                },
                // 机构列表
                mechanismList: [],
                // 出院科室列表
                departmentList: [],
                // 编码员列表
                coderList: [],
                // 出院时间选择
                datePickerOut: {
                    // 时间单位
                    timeUnit: 'month',
                    // 年月
                    yearMonth: '',
                    // 季度
                    quarter: '1'
                },
                // 上传时间选择
                datePickerUpload: {
                    // 时间单位
                    timeUnit: 'month',
                    // 年月
                    yearMonth: '',
                    // 季度
                    quarter: '1'
                },
                // cascader的key值，避免组件报错
                isResouceShow: 0,
                // 当前是数据管理页面病案包
                isDataPackge: false,
                // 是否显示末次统计
                isShowLast: true,
                // 参数配置查看病案时间
                viewDeadlineDays: '',
                // 总览质控明细是否显示末次统计
                overviewIsShowLast: true
            }
        },
        computed: {
            isPackage () {
                return this.$store.state.user.isDataPackage
            }
        },
        watch: {
            $route () {
                this.overviewIsShowLast = true
                // 路由变化和计算属性重复触发initData，F5刷新不走路由，为防止监听不到路由变化，加上了计算属性
                this.initData()
            },
            isPackage () {
                this.initData()
            }
        },
        created () {
            this.initData()
        },
        mounted () {
            Bus.$on('changeShowLast', (val) => {
                this.overviewIsShowLast = val
            })
        },
        methods: {
            /**
             * 初始化数据源
             */
            initData () {
                this.isDataPackge = JSON.parse(Cookie.get('isPackage'))
                this.isShowLast = !this.$route.meta.noLast
                this.mechanismList = this.getLocalStorage('userInfo', 'mechanism')
                // 判断是否是数据管理页面病案包
                if (this.isDataPackge) {
                    this.setDataMangage()
                } else {
                    this.setOtherPage()
                }
                // 如果没有保存过，执行保存初始化操作
                this.submitSearch('init')
            },
            /**
             * 设置全局初始值
             */
            setOtherPage () {
                // 有默认值
                if (this.getLocalStorage('globalSearchUnit')) {
                    // 机构被清除，重新选择
                    if (this.getLocalStorage('globalSearch', 'orgId') === '') {
                        this.setMechanismId()
                    } else {
                        let params = this.getLocalStorage('globalSearch')
                        this.form = {
                            mechanism: params.orgId,
                            department: params.departmentId,
                            coder: params.bmy,
                            lastCount: params.isLast,
                            cykb: params.cykb,
                            cybf: params.cybf
                        }
                        if (!this.coderList.length) {
                            this.form.coder = ''
                        }
                        this.datePickerOut = this.getLocalStorage('globalSearchUnit')
                    }
                } else {
                    let date = new Date()
                    this.datePickerOut.yearMonth = `${date.getFullYear()}-${date.getMonth() + 1}-01`
                    this.setMechanismId()
                }
                this.setDepartmentList(this.form.mechanism, this.form.department)
            },
            /**
             * 设置数据管理页面初始值
             */
            setDataMangage () {
                // 有默认值
                if (this.getLocalStorage('globalSearchUploadUnit')) {
                    let params = this.getLocalStorage('globalSearch')
                    this.form.mechanism = params.orgId
                    this.datePickerUpload = this.getLocalStorage('globalSearchUploadUnit')
                } else {
                    let date = new Date()
                    this.datePickerUpload.yearMonth = `${date.getFullYear()}-${date.getMonth() + 1}-01`
                    this.setMechanismId()
                }
            },
            /**
             * 设置机构id
             */
            setMechanismId () {
                if (this.mechanismList.length) {
                    if (this.getLocalStorage('userMechanism', 'id') && this.hasMechanismId(this.getLocalStorage('userMechanism', 'id'))) {
                        this.form.mechanism = this.getLocalStorage('userMechanism', 'id')
                    } else {
                        this.form.mechanism = this.mechanismList[0].id
                    }
                }
            },
            /**
             * 判断所属机构是否在组织机构中
             * @param id 所属机构id
             */
            hasMechanismId (id) {
                let res = this.mechanismList.filter(item => item.id === id)
                return res.length !== 0
            },
            /**
             * 选择机构后设置出院科室内容
             * @param val 选中的id
             * @param department 科室id
             */
            setDepartmentList (val, department) {
                this.isResouceShow++
                this.form.department = ''
                this.departmentList = []
                let checkAuth = Number(this.getLocalStorage('userInfo', 'checkAuth'))
                let index = this.mechanismList.findIndex(item => item.id === val)
                let departmentList = []
                if (this.mechanismList.length) {
                    departmentList = this.mechanismList[index].organDep
                    this.viewDeadlineDays = this.mechanismList[index].viewDeadlineDays
                    if (departmentList.length && checkAuth !== 1 && checkAuth !== 2 && departmentList[0].id !== '0') {
                        departmentList.unshift({
                            id: '0',
                            name: '全部科室'
                        })
                    }
                }
                this.departmentList = departmentList
                // 判断的是'' 和 undefined
                if (department) {
                    this.form.department = department
                } else if (departmentList.length && (checkAuth === 1 || checkAuth === 2)) {
                    this.form.department = departmentList[0].id
                } else {
                    this.form.department = departmentList.length ? '0' : ''
                }
                this.coderList = []
                // 请求编码员列表
                getCoderList(val).then(res => {
                    if (res.code.toString() === '200') {
                        if (res.data) {
                            let coderList = []
                            res.data.forEach((item, index) => {
                                if (item && item !== '') {
                                    coderList.push({
                                        value: index + 1,
                                        label: item
                                    })
                                }
                            })
                            this.coderList = coderList
                            if (!this.coderList.length) {
                                this.form.coder = ''
                            }
                        }
                    } else {
                        this.$message.error(res.message)
                    }
                })
            },
            /**
             * 提交查询
             * @param init 是否是初始化
             */
            submitSearch (init) {
                let params = {
                    // 机构id
                    orgId: this.form.mechanism,
                    // 出院科室
                    departmentId: this.form.department,
                    // 出院科室编码
                    cykb: this.form.cykb,
                    // 出院科室名称
                    cybf: this.form.cybf,
                    // 编码员
                    bmy: this.form.coder === '0' ? '' : this.form.coder,
                    // 开始时间
                    startDate: '',
                    // 结束时间
                    endDate: '',
                    // 是否末次统计
                    isLast: this.form.lastCount
                }
                if (this.isDataPackge) {
                    params = this.getPickerTime(params, 'datePickerUpload')
                    localStorage.setItem('globalSearchUploadUnit', JSON.stringify(this.datePickerUpload))
                } else {
                    // 获取选中节点
                    if (this.form.department !== '0' && this.form.department !== '') {
                        // 如果为null就表示页面还未初始化完成，属于初次进来，根据需求选中第一个科室
                        params.departmentId = this.form.department
                        if (this.$refs['cascaderSelector']) {
                            let node = this.$refs['cascaderSelector'].getCheckedNodes()
                            params.cykb = node[0].data.code
                            params.cybf = node[0].data.name
                        } else {
                            let depItem = this.departmentList.filter(item => item.id === this.form.department)
                            params.cykb = depItem[0].code
                            params.cybf = depItem[0].name
                        }
                    } else {
                        this.form.department = '0'
                        params.departmentId = ''
                        params.cykb = ''
                        params.cybf = ''
                    }
                    // 获取对应时间选择器时间
                    params = this.getPickerTime(params, 'datePickerOut')
                    localStorage.setItem('globalSearchUnit', JSON.stringify(this.datePickerOut))
                }
                localStorage.setItem('globalSearch', JSON.stringify(params))
                localStorage.setItem('viewDeadlineDays', this.viewDeadlineDays)
                Bus.$emit('globalSearch')
            },
            /**
             * 获取时间
             * @param params 参数对象
             * @param Pname 时间选择器属性名字
             */
            getPickerTime (params, Pname) {
                let time = this[Pname].yearMonth
                let timeArr = time.split('-')
                let year = timeArr[0]
                let month = timeArr[1]
                // 每月天数
                let d = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31]
                if (this[Pname].timeUnit === 'month') {
                    params.startDate = time
                    // 判断闰年二月
                    if (parseInt(month) === 2 && year % 4 === 0 && (year % 100 !== 0 || year % 400 === 0)) {
                        params.endDate = `${year}-${month}-${d[parseInt(month) - 1] + 1}`
                    } else {
                        params.endDate = `${year}-${month}-${d[parseInt(month) - 1]}`
                    }
                } else if (this[Pname].timeUnit === 'quarter') {
                    // 判断季度
                    switch (this[Pname].quarter) {
                    case '1':
                        params.startDate = `${year}-01-01`
                        params.endDate = `${year}-03-31`
                        break
                    case '2':
                        params.startDate = `${year}-04-01`
                        params.endDate = `${year}-06-30`
                        break
                    case '3':
                        params.startDate = `${year}-07-01`
                        params.endDate = `${year}-09-30`
                        break
                    case '4':
                        params.startDate = `${year}-10-01`
                        params.endDate = `${year}-12-31`
                        break
                    }
                } else if (this[Pname].timeUnit === 'year') {
                    params.startDate = `${year}-01-01`
                    params.endDate = `${year}-12-31`
                }
                return params
            }
        },
        beforeDestroy () {
            Bus.$off('changeShowLast')
        }
    }
</script>

<style scoped lang="scss">
    .global-search-container {
        display: flex;
        justify-content: space-between;
        align-items: center;
        padding: 10px 28px 10px 10px;
        background: #f6f6f6;
        .global-search {
            display: flex;
            justify-content: flex-start;
            align-items: center;
            .el-form-item {
                margin-bottom: 0;
                margin-right: 10px;
                /deep/.el-form-item__label {
                    padding: 0;
                }
            }
            .mechanism {
                width: 240px;
            }
            .go-out {
                width: 200px;
            }
            .coder {
                width: 120px;
            }
            .time-unit {
                width: 90px;
            }
            .year-month {
                width: 120px;
            }
            .quarter {
                width: 120px;
            }
        }
    }
</style>
